package com.example.development.mysqlStudy.controller;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Scanner;


/**
 * 代码生成器演示
 * @author huangyongfeng
 *
 */
public class MpGenerator {
	
    /**
     * RUN THIS
     */
    public static void main(String[] args) {
    	
    	final String projectName = "cmu-mybatis";
//    	String schemaName = "";
//    	String moduleName = "";
    	
//    	String setTablePrefix = "sys";
//    	String tableName = "sys_config";
    	
    	String setTablePrefix = "";
    	String tableName = "user";
    	
//      String setTablePrefix = "bank";
//      String tableName = "bank_transfer_record";

    	
    	String driverName = "com.mysql.cj.jdbc.Driver";
    	String username = "root";
    	String password ="admin";
    	String url = "jdbc:mysql://192.168.0.145/development?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8";
//    	String url = "jdbc:mysql://127.0.0.1/ybt_cmu?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8";
    	String packageParent= "com.ybt.cmu";
    	
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        final String projectPath = System.getProperty("user.dir");
//        System.out.println("projectPath===>"+projectPath.substring(0, projectPath.lastIndexOf(File.separatorChar)));
        final String path = projectPath.substring(0, projectPath.lastIndexOf(File.separatorChar));
        
//        final String projectName = scanner("生成的工程名");
        gc.setOutputDir(path + File.separatorChar + projectName + File.separatorChar+"src"+File.separatorChar+"main"+File.separatorChar+"java");
        gc.setAuthor("ybt");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setEntityName("%sDO");
        gc.setServiceName("%sDao");
        gc.setServiceImplName("%sDaoService");
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
       
        
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
//        dsc.setSchemaName(scanner("数据库schemaname名"));
//        dsc.setSchemaName(schemaName);
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setUrl(url);
        mpg.setDataSource(dsc);

        // 包配置
        final PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("功能模块名"));
//        pc.setModuleName(moduleName);
        pc.setEntity("mapper.domain");
        pc.setParent(packageParent);
        pc.setService("mapper.dao");
        pc.setServiceImpl("mapper.dao.service");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
       
        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
//         String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
//        List<FileOutConfig> focList = new ArrayList<>();
//        // 自定义配置会被优先输出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
//                return path + "/"+projectName + "/src/main/java/com/business/dao/" + pc.getModuleName()
//                        + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
        
//        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null).setController(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setInclude(scanner("表名"));
        strategy.setInclude(tableName);
        strategy.setTablePrefix(setTablePrefix);
//        strategy.setEntityTableFieldAnnotationEnable(true);
        
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
    
	
	
	/**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        @SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

}
